<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use app\common\logic\wechat\WechatUtil;
use app\common\logic\WechatLogic;

class WxApp extends Base
{
    private $wx_user;

    function __construct()
    {
        parent::__construct();
        $this->wx_user = Db::name('wx_app_set')->where('1=1')->find();
    }

    public function index()
    {
        $wx_user = $this->wx_user;
        header("Location:".url('WxApp/setting',['id'=>$wx_user['id']]));
        exit;
    }

    public function setting()
    {
        $id = input('id');

        $wechat = Db::name('wx_app_set')->where('1=1')->find();
        if (IS_POST) {
            $post_data = input('');
            $data = [];
            $data['appid'] = $post_data['appid'];
            $data['appsecret'] = $post_data['appsecret'];
            $data['wxname'] = $post_data['wxname'];
            $data['qrcode'] = $post_data['qrcode'];
            $data['token'] = $post_data['token'];
            $data['encode'] = $post_data['encode'];
            $data['web_expires'] = 0;
            $data['create_time'] = time();
            if($id){
                $row = Db::name('wx_app_set')->where(array('id' => $id))->update($data);
            }else{
                $row = Db::name('wx_app_set')->insertGetId($data);
            }

            return json(['status'=>1,'msg'=>'修改成功','url'=>url('WxApp/setting')]);
        }


        $domain = getCurUrl();
        $web_info = [
            'ip' => $_SERVER['REMOTE_ADDR'],
            'https_url' => $domain,
            'wechat_url' => $domain.'/home/wechat/index',
        ];
        View::assign('info', $wechat);
        View::assign('web_info', $web_info);
        return View::fetch();
    }


    /**
     * 模板消息
     */
    public function template_msg()
    {
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            $count = Db::name('wx_tpl_msg')->alias('p')->where($map)->count();

            $field = 'p.*';
            $list = Db::name('wx_tpl_msg')
                ->alias('p')
                ->field($field)
                ->where($map)
                ->order('p.id desc ')
                ->page($page,$limit)
                ->select();
            foreach($list as $k=>$v){
                $list[$k]['w_time'] = date('Y-m-d H:i:s',$v['w_time']);
            }
            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
        }
        return $this->fetch('template_msg_new');
    }
    public function edit_tpl_msg(){
        $id = input('id');
        if(IS_POST){
            $params = input();
            $data = [];
            $data['title'] = $params['title']??'';
            $data['template_sn'] = $params['template_sn'];
            $data['template_id'] = $params['template_id'];
            $data['remark'] = $params['remark'];
            $data['type'] = $params['type'];
            $data['w_time'] = $params['w_time'];
            $data['status'] = $params['status'];
            if($id){
                Db::name('wx_tpl_msg')->where('id',$id)->update($data);
            }else{
                Db::name('wx_tpl_msg')->insert($data);
            }
        }else{
            $info = Db::name('wx_tpl_msg')->where('id',$id)->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }

    /**
     * 设置模板消息
     */
    public function set_template_msg()
    {
        $template_sn = input('template_sn');
        $is_use = input('is_use/d');
        $remark = input('remark');

        $data = [];
        !is_null($is_use) && $data['is_use'] = $is_use;
        !is_null($remark) && $data['remark'] = $remark;

        $logic = new WechatLogic;
        $return = $logic->setTemplateMsg($template_sn, $data);
        $this->ajaxReturn($return);
    }

    /**
     * 重置模板消息
     */
    public function reset_template_msg()
    {
        $template_sn = input('template_sn');

        $logic = new WechatLogic;
        $return = $logic->resetTemplateMsg($template_sn);

        $this->ajaxReturn($return);
    }

    //下载微信V3支付用的平台证书
    public function wechatkey($aid,$apiV3key,$wxpay_mchid,$wxpay_apiclient_key,$wxpay_serial_no){
        $certificate = ROOT_PATH.'vendor'.DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'CertificateDownloader.php';//生成证书的工具路径
        $apiclient_key = ROOT_PATH.$wxpay_apiclient_key;//商户私钥
        $mchSerialNo = $wxpay_serial_no;//商户私钥证书序列号
        $out_path = ROOT_PATH.'upload'.DIRECTORY_SEPARATOR.$aid.DIRECTORY_SEPARATOR.'wechatkey'.DIRECTORY_SEPARATOR;
        if(!file_exists($out_path)){
            mk_dir($out_path, 0775);
        }else{
            //先删除旧的证书文件
            $old_files = scandir($out_path);
            foreach($old_files as $old_file){
                unlink($out_path.$old_file);
            }
        }
        //dump('php -f '.$certificate.' -- -k '.$apiV3key.' -m '.$wxpay_mchid.' -f '.$apiclient_key.' -s '.$mchSerialNo.' '.$out_path);
        //此处好像需要php版本才可以，待确认 todo
        $res = shell_exec('php -f '.$certificate.' -- -k '.$apiV3key.' -m '.$wxpay_mchid.' -f '.$apiclient_key.' -s '.$mchSerialNo.' -o '.$out_path);
        $files = scandir($out_path);
        $key_file = '';
        foreach($files as $file){
            if(strpos($file,'.pem')!==false){
                $key_file = $file;
                break;
            }
        }
        $new_file_name = 'wechatkey_'.$aid.'.pem';
        if (rename($out_path.$key_file, $out_path.$new_file_name)) {
            $new_file = str_replace(ROOT_PATH, '', $out_path.$new_file_name);
            return ['status'=>1,'msg'=>'下载成功','data'=>$new_file];
        } else {
            return ['status'=>0,'msg'=>'下载失败，请手动上传'];
        }
    }
}